Skip to content

Normalize IPv6 addresses on read and write operations. Closes #1683 - #1735

Merged
regulartim merged 5 commits into
GreedyBear-Project:developfrom
suvani-ctrl:fix/1683-normalize-ipv6
Nov 11, 2026
Merged

regulartim merged 5 commits into
GreedyBear-Project:developfrom
suvani-ctrl:fix/1683-normalize-ipv6

Conversation

@suvani-ctrl

Copy link
Copy Markdown
Contributor

Description

Introduces a IP normalization utility and applies it consistently across read and write operations.

  • IP Normalization (normalize_ip): Added a utility in greedybear/utils.py that formats native IPv6 addresses into lowercase compressed forms and safely converts IPv4-mapped IPv6 addresses (e.g., ::ffff:1.2.3.4) back to standard IPv4.
  • Data Ingestion & Pipeline: Updated ingestion flows (Hit, bucket updaters, and raw event processing) to store IP addresses in their canonical normalized form, preventing fragmentation in analytics and trending metrics.
  • Repositories & Lookups: Enforced address normalization across IocRepository and SensorRepository queries so that equivalent formatting variants correctly resolve to existing database records.
  • API Serializers & Views: Integrated validation and request extraction normalization for enrichment requests, event submissions, and session endpoints.
  • Testing: Added comprehensive unit test suites covering edge cases, equivalent formats, and bulk repository operations.

Related issues

Closes #1683

Type of change

  • Bug fix (non-breaking change which fixes an issue).
  • New feature (non-breaking change which adds functionality).
  • Breaking change (fix or feature that would cause existing functionality to not work as expected).
  • Chore (refactoring, dependency updates, CI/CD changes, code cleanup, docs-only changes).

Checklist

Please complete this checklist carefully. It helps guide your contribution and lets maintainers verify that all requirements are met.

Formalities

  • I have read and understood the rules about how to Contribute to this project.
  • I chose an appropriate title for the pull request in the form: <feature name>. Closes #999
  • My branch is based on develop.
  • The pull request is for the branch develop.
  • I have reviewed and verified any LLM-generated code included in this PR.

Docs and tests

  • I documented my code changes with docstrings and/or comments.
  • [] I have checked if my changes affect user-facing behavior that is described in the docs. If so, I also included an update to the wiki in the description of this PR.
  • Linter (Ruff) gave 0 errors. If you have correctly installed pre-commit, it does these checks and adjustments on your behalf.
  • I have added tests for the feature/bug I solved.
  • All the tests gave 0 errors.

GUI changes

Ignore this section if you did not make any changes to the GUI.

  • I have provided a screenshot of the result in the PR.
  • I have created new frontend tests for the new component or updated existing ones.

Review process

  • We encourage you to create a draft PR first, even when your changes are incomplete. This way you refine your code while we can track your progress and actively review and help.
  • If you think your draft PR is ready to be reviewed by the maintainers, click the corresponding button. Your draft PR will become a real PR.
  • If your changes decrease the overall tests coverage (you will know after the Codecov CI job is done), you should add the required tests to fix the problem.
  • Every time you make changes to the PR and you think the work is done, you should explicitly ask for a review. After receiving a "change request", address the feedback and click "request re-review" next to the reviewer's profile picture at the top right.

@suvani-ctrl
suvani-ctrl marked this pull request as draft October 12, 2026 16:27
@suvani-ctrl

Copy link
Copy Markdown
Contributor Author

Hi @regulartim! I’ve opened a draft PR for this.

I added normalize_ip() in utils.py using the standard ipaddress module (.compressed for lowercase compressed IPv6, .ipv4_mapped to convert mapped addresses back to IPv4). Since #1650 every hit goes through Hit, so I normalize src_ip there, and I also covered the API inputs (events, sensors, enrichment, Cowrie session queries) and the IOC repository lookups. Tests are added for each. Please let me know

@suvani-ctrl
suvani-ctrl marked this pull request as ready for review October 14, 2026 08:56

@regulartim regulartim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @suvani-ctrl ! Thank you, good job!

Could you please check for redundant calls of normalize_ip()? Every function that gets is data from a Hit object, does not need to call it again, right? So please check, e.g. group_valid_hits_by_ip, _bucket_key_from_hit and _normalize_raw_event_to_hit are candidates for redundant calls.

Comment thread greedybear/utils.py
Comment on lines +36 to +52
def normalize_ip(ip_str: str) -> str:
"""
Normalizes an IP address string.
IPv4 addresses are returned unchanged, IPv4-mapped IPv6 addresses are
converted back to IPv4 and other IPv6 addresses are returned in
lower-case compressed format while invalid input is stripped.
"""
ip_str = ip_str.strip()
try:
ip = ip_address(ip_str)
except ValueError:
return ip_str

if ip.version == 6 and ip.ipv4_mapped:
return str(ip.ipv4_mapped)

return ip.compressed

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! 👍

Comment on lines +51 to +54
# equivalent IP spellings must map to one canonical form everywhere downstream
src_ip = self._data.get("src_ip")
if isinstance(src_ip, str) and src_ip.strip():
self._data["src_ip"] = normalize_ip(src_ip)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The class docstring says it's a read-only mapping but we're changing it here (and I think it's the right pace to do that). Please update the docstring.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated.

@suvani-ctrl
suvani-ctrl force-pushed the fix/1683-normalize-ipv6 branch 2 times, most recently from 267dede to 9a372f2 Compare October 20, 2026 09:10

@regulartim regulartim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @suvani-ctrl ! Thanks for implementing the changes. Two things need to be addressed before we can merge (sorry, I did not find them last time):

  1. Cowrie and Tanner create IOCs from urlparse(...).hostname. This might lead to an IPv6 in IOC.name that is uncompressed and might cause an IntegrityError in the future. So we must also normalize IPs on the write path. I'd suggest to do this either in IocProcessor.add_ioc or in IocRepository.save. That way it would cover Cowrie, Tanner and iocs_from_hits together. What do you think?
  2. Please merge (or rebase on) the recent develop. You will find a new that in BaseEnrichmentJob._match_iocs there is a new IOC.namematching without normalization. Please fix that.

@suvani-ctrl
suvani-ctrl force-pushed the fix/1683-normalize-ipv6 branch from 9a372f2 to 7d18d33 Compare November 2, 2026 05:58
@suvani-ctrl

Copy link
Copy Markdown
Contributor Author

Hey @suvani-ctrl ! Thanks for implementing the changes. Two things need to be addressed before we can merge (sorry, I did not find them last time):

  1. Cowrie and Tanner create IOCs from urlparse(...).hostname. This might lead to an IPv6 in IOC.name that is uncompressed and might cause an IntegrityError in the future. So we must also normalize IPs on the write path. I'd suggest to do this either in IocProcessor.add_ioc or in IocRepository.save. That way it would cover Cowrie, Tanner and iocs_from_hits together. What do you think?
  2. Please merge (or rebase on) the recent develop. You will find a new that in BaseEnrichmentJob._match_iocs there is a new IOC.namematching without normalization. Please fix that.

Hi @regulartim, thanks for the feedback!

So far, the changes include:

1. Write-path IP normalization: Added normalize_ip(...) to IocRepository.save, IocProcessor.add_ioc, and Hit.__init__ to ensure IPs from Cowrie and Tanner are normalized as early as possible, before reaching the database. I also fixed a related issue in add_ioc, where the sensor-cache check compared raw ioc.name values against normalized cache entries. Here the normalizing earlier ensures uncompressed IPs are matched correctly.

2. Enrichment query matching: Updated BaseEnrichmentJob._match_iocs to normalize IP keys before filtering against IOC.name.

3. Rebase and tests: Rebased the changes onto develop as requested and added three tests covering write-path normalization, sensor-cache matching, and _match_iocs.

@regulartim regulartim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @suvani-ctrl ! Thanks for implementing the changes. I found another bug: _match_iocs now normalizes the keys before the query, so it returns the normalized IOC.name, right? The callers then use that name to index the original dictionary, which still has the un-normalized keys. This results in a key error. I'll add a test case for that.

A fix could be to normalize the keys where the dict is built, e.g. in _parse_feed or get_entries_by_ip. What do you think?

@suvani-ctrl

suvani-ctrl commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Hey @suvani-ctrl ! Thanks for implementing the changes. I found another bug: _match_iocs now normalizes the keys before the query, so it returns the normalized IOC.name, right? The callers then use that name to index the original dictionary, which still has the un-normalized keys. This results in a key error. I'll add a test case for that.

A fix could be to normalize the keys where the dict is built, e.g. in _parse_feed or get_entries_by_ip. What do you think?

Hello @regulartim
I agree that normalizing where the dict is built is the cleaner fix. That way there’s a single place per source, and _match_iocs doesn’t need to normalize at all (the same idea as the redundant calls we removed before). I’d normalize the keys in get_entries_by_ip for FireHOL, and in both _parse_feed methods for AbuseIPDB and ThreatFox.

One thing about your test, it builds feed_by_ip & passes it straight to _match_iocs/_build_tag_entries, so it skips get_entries_by_ip. With this fix it would still fail. I’d adapt it to store the IP in a FireHolList row and build the dict via get_entries_by_ip(), so the test goes through the real code path. Is that OK with you, or would you rather keep the test as is and have the matching code handle un-normalized keys?

@regulartim

Copy link
Copy Markdown
Member

Hi @suvani-ctrl !

Is that OK with you, or would you rather keep the test as is and have the matching code handle un-normalized keys?

That is Ok for me, please go ahead! :)

@suvani-ctrl
suvani-ctrl force-pushed the fix/1683-normalize-ipv6 branch from 43e67b2 to a077007 Compare November 9, 2026 18:28

@regulartim regulartim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @suvani-ctrl ! This looks very solid now. I am happy to merge it. Thanks for your work, well done! 👍

@regulartim
regulartim merged commit 7dd4f54 into GreedyBear-Project:develop Nov 11, 2026
6 checks passed
@suvani-ctrl

Copy link
Copy Markdown
Contributor Author

Hey @suvani-ctrl ! This looks very solid now. I am happy to merge it. Thanks for your work, well done! 👍

Thankyouu @regulartim : )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants